package com.yingxin.yxerp.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.sys.entity.DingMessageSet;
import com.yingxin.yxerp.module.sys.mapper.DingMessageSetMapper;
import com.yingxin.yxerp.module.sys.service.IDingMessageSetService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 钉钉发送消息回话id设置 服务实现类
 * @author jiangxudong
 * @since 2022-05-13
 */

@Service
public class DingMessageSetServiceImpl
        extends ServiceImpl<DingMessageSetMapper, DingMessageSet>
        implements IDingMessageSetService {

    /**
    * 创建
    */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void create(DingMessageSet dingMessageSet) {
        checkChatType(dingMessageSet,null);
        save(dingMessageSet);
    }

    /**
    * 修改
    */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void update(DingMessageSet dingMessageSet) {
        checkChatType(dingMessageSet,dingMessageSet.getId());
        updateById(dingMessageSet);
    }

    /**
    * 删除
    */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void delete(DingMessageSet dingMessageSet) {
        removeById(dingMessageSet);
    }

    @Override
    public DingMessageSet getDingMessageSetByType(String chatType) {
        QueryWrapper<DingMessageSet> qw = new QueryWrapper<>();
        qw.lambda().eq(DingMessageSet::getChatType,chatType);
        DingMessageSet set = getOne(qw);
        return getOne(qw);
    }

    public void checkChatType(DingMessageSet entity, String id) {
        QueryWrapper<DingMessageSet> qw = new QueryWrapper<>();
        qw.lambda().eq(DingMessageSet::getChatType,entity.getChatType());
        DingMessageSet temp = getOne(qw);
        if (null != temp && !temp.getId().equals(id)){
            throw new BizException("会话类型不能重复!");
        }
    }

}
